<template>
  <div class="dashboard">
    <div style="height: 100%; text-align: center; margin: 300px auto;">
      <div style="width: 100%; margin-bottom: 10px;">
        <span>url:</span>
        <textarea v-model="ipt" rows="6" />
      </div>
      <div style="width: 100%; margin-bottom: 10px;">
        <span>文件夹名称:</span>
        <input v-model="wjj" style="height: 40px;" />
      </div>
      <div style="width: 100%; margin-bottom: 10px;">
        <span>数量:</span>
        <input type="number" style="height: 40px;" v-model="num" />
      </div>
      <div style="width: 100%; margin-bottom: 10px;">
        <span>开始:</span>
        <input type="number" style="height: 40px;" v-model="num1" />
      </div>
      <button @click="doClick">执行</button>
    </div>
  </div>
</template>

<script>
import JSZip from 'jszip'
import FileSaver from 'file-saver'
export default {
  name: 'Dashboard',
  data () {
    return {
      ipt: '',
      num: 0,
      num1: 0,
      wjj: ''
    }
  },
  methods: {
    getB64Img (src) {
      return new Promise((resolve, reject) => {
        let canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        const img = new Image()
        img.crossOrigin = 'Access-Control-Allow-Origin'
        img.onload = () => {
          canvas.height = img.height
          canvas.width = img.width
          ctx.drawImage(img, 0, 0)
          const url = canvas.toDataURL('image/png')
          const ddh = url.split(',')[1]
          resolve(ddh)
          canvas = null
        }
        img.src = src
      })
    },
    doClick () {
      const urls = []
      for (let i = 0; i < this.num; i++) {
        // if ([24, 32, 57].includes(i)) {
        //   continue
        // }
        const number = this.num1 * 1 + i
        urls.push(this.getB64Img(`${this.ipt}/${number}.jpg`))
        // urls.push(this.getB64Img(`${this.ipt}/${number}.com`))
      }
      const wjj = `${this.wjj}${this.num}p`
      Promise.all(urls).then(res => {
        const zip = new JSZip()
        const img = zip.folder(wjj)
        let n = 0
        res.map(p => {
          const i = n++
          img.file(`${i}.png`, p, { base64: true })
        })
        zip.generateAsync({ type: 'blob' }).then(cont => {
          FileSaver.saveAs(cont, `${wjj}.zip`)
        })
      })
    }
  }
}
</script>

<style lang="scss">

</style>
